from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import ImageSerialize
from rest_framework.response import Response
from shortuuid import uuid
import os
from django.conf import settings
from rest_framework.viewsets import ViewSet

# Create your views here.
class ImageView(APIView):
    def post(self,request):
        # 对前端上传上来的图片进行校验
        serialize = ImageSerialize(data=request.data)
        if serialize.is_valid():
            file = serialize.validated_data.get('image')
            # os.path.splitext() 根据文件后缀名进行分割
            filename = uuid() + os.path.splitext(file.name)[-1]
            # 保存的文件路径
            # "/media/Vn4XfkXtYiNvytnhVBGTjs.jpg"
            # Vn4XfkXtYiNvytnhVBGTjs.jpg
            path = settings.MEDIA_ROOT / filename
            try:
                # fp是一个指针对象
                with open(path,'wb') as fp:
                    for chunk in file.chunks():
                        fp.write(chunk)
            except Exception:
                return Response({
                        "errno": 1, # 只要不等于0就行
                        "message": "图片保存失败！"
                    })
            # 成功上传
            file_url = settings.MEDIA_URL + filename
            return Response({
                "errno": 0, # 注意：值是数字，不能是字符串
                "data": {
                    "url": file_url, # 图片src ，必须
                    "alt": "", # 图片描述文字，非必须
                    "href": file_url # 图片的链接，非必须
                }
            })
        else:
            print(serialize.errors)
            # return Response({
            #     "errno": 1, # 只要不等于0就行
            #     "message": "图片保存失败！"
            # })
            return Response({
                "errno": 1  , # 只要不等于0就行
                "message": list(serialize.errors.values())[0][0]
            })